const fs = require('fs');
const readline = require('readline');

function parseSalesReport(filePath) {
    return new Promise((resolve, reject) => {
        // 创建读取文件流
        const fileStream = fs.createReadStream(filePath);

        // 创建 readline 接口
        const rl = readline.createInterface({
            input: fileStream,
            crlfDelay: Infinity
        });

        // 初始化数据数组
        const reportData = [];

        // 解析每一行数据
        rl.on('line', (line) => {
            // 分割行数据
            const data = line.split('\t');

            // 跳过标题行
            if (data[0] === 'Provider') {
                return;
            }

            //打印 reportData 第一行
            // console.log(`reportData date: ${formatDate(data[9])}-${formatDate(data[10])}`);

            // 将解析后的数据添加到数组中
            reportData.push({
                provider: data[0],
                providerCountry: data[1],
                sku: data[2],
                developer: data[3],
                title: data[4],
                version: data[5],
                productTypeIdentifier: data[6],
                units: parseInt(data[7], 10),
                developerProceeds: parseFloat(data[8]),
                beginDate: formatDate(data[9]),
                endDate: formatDate(data[10]),
                customerCurrency: data[11],
                countryCode: data[12],
                currencyOfProceeds: data[13],
                appleIdentifier: data[14],
                customerPrice: parseFloat(data[15]),
                promoCode: data[16],
                parentIdentifier: data[17],
                subscription: data[18],
                period: data[19],
                category: data[20],
                cmb: data[21],
                device: data[22],
                supportedPlatforms: data[23],
                proceedsReason: data[24],
                preservedPricing: data[25],
                client: data[26],
                orderType: data[27]
            });
        });

        // 读取完成后返回数据
        rl.on('close', () => {
            resolve(reportData);
        });

        rl.on('error', (error) => {
            reject(error);
        });
    });
}

// 日期格式转换函数
function formatDate(dateStr) {
    const [month, day, year] = dateStr.split('/');
    return `${year}-${month}-${day}`;
}

// 导出函数
module.exports = parseSalesReport;